//
//  InitializeViewController.m
//  HeWeiZhiNeng
//
//  Created by chengzhang Yan on 2017/11/30.
//  Copyright © 2017年 YanCeyMichael.github.io. All rights reserved.
//

#import "InitializeViewController.h"
#import "YanCNewFeatureViewController.h"
#import "PersonalCenterViewController.h"
#import "RXLSideSlipViewController.h"
#import "BaseTabBarController.h"
#import "LoginViewController.h"

@interface InitializeViewController ()
@property (nonatomic, strong)Reachability *routerReachability;
@property (nonatomic, strong)Reachability *hostReachability;
@end

@implementation InitializeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self appleReachabilityTest];
    [self addTheScreenBgView];
    [self switchRootViewController];
}

- (void)addTheScreenBgView
{
    UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bgImgView.image = [UIImage imageNamed:@"LaunchScreen"];
    [self.view addSubview:bgImgView];
}


- (void)switchRootViewController
{
    NSString *key = @"CFBundleShortVersionString";
    // 获得当前软件的版本号
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
    // 获得沙盒中存储的版本号
    NSString *sanboxVersion = [[NSUserDefaults standardUserDefaults] stringForKey:key];
    
    if ([currentVersion isEqualToString:sanboxVersion]) { // 本地版本号相同
        
//        LoginViewController *loginVC = [[LoginViewController alloc] init];
//        RTRootNavigationController *navi = [[RTRootNavigationController alloc] initWithRootViewController:loginVC];
//        [UIApplication sharedApplication].keyWindow.rootViewController = navi;

        BaseTabBarController *tabbarVC = [[BaseTabBarController alloc] init];
        PersonalCenterViewController *personVC = [[PersonalCenterViewController alloc] init];
        RTRootNavigationController *naVC = [[RTRootNavigationController alloc] initWithRootViewController:personVC];
        personVC.navigationController.navigationBar.hidden = YES;
        RXLSideSlipViewController *RXLVC = [[RXLSideSlipViewController alloc] initWithContentViewController:tabbarVC leftMenuViewController:naVC rightMenuViewController:nil];
                
        //创建动画
        CATransition *animation = [CATransition animation];
        animation.type = kCATransitionPush;
        animation.duration = 1.5f;
        [[UIApplication sharedApplication].delegate.window.layer addAnimation:animation forKey:nil];
        
        [UIApplication sharedApplication].delegate.window.rootViewController = RXLVC;

    }
    else { // 本地版本号不同, 显示新特性
        YanCNewFeatureViewController *newFeatureVC = [[YanCNewFeatureViewController alloc] init];
        [UIApplication sharedApplication].delegate.window.rootViewController = newFeatureVC;
        // 将当前的版本号存进沙盒
        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    }
}

#pragma mark - 网络监测
#pragma mark ----- 网络检测1(当检测到网络断开时会间隔15s再次检测，如果还是断开则弹窗提醒，防止过于频繁操作) -----
- (void)appleReachabilityTest {
    /// Reachability使用了通知，当网络状态发生变化时发送通知kReachabilityChangedNotification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appReachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    // 被通知函数运行的线程应该由startNotifier函数执行的线程决定
    typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *remoteHostName = @"www.bing.com";
        weakSelf.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
        [weakSelf.hostReachability startNotifier];
        
        weakSelf.routerReachability = [Reachability reachabilityForInternetConnection];
        [weakSelf.routerReachability startNotifier];
        // 开启当前线程消息循环
        [[NSRunLoop currentRunLoop] run];
    });
}

#pragma mark ----- 网络检测2(网络状态发生变化时调用) -----
- (void)appReachabilityChanged:(NSNotification *)notification{
    Reachability *reach = [notification object];
    if([reach isKindOfClass:[Reachability class]]){
        NetworkStatus status = [reach currentReachabilityStatus];
        // 两种检测:路由与服务器是否可达  三种状态:手机流量联网、WiFi联网、没有联网
        if (reach == self.routerReachability) {
            if (status == NotReachable) {
                [SingleManager shareManager].NetworkStatus = NO;
                // 3秒后再次检测
                [self performSelector:@selector(appReachabilityChangedConfirm) withObject:nil afterDelay:3];
            } else if (status == ReachableViaWiFi) {
                [SingleManager shareManager].NetworkStatus = YES;
            } else if (status == ReachableViaWWAN) {
                [SingleManager shareManager].NetworkStatus = YES;
            }
        }
        if (reach == self.hostReachability) {
            if (status == NotReachable) {
                [self performSelector:@selector(appReachabilityChangedConfirm) withObject:nil afterDelay:3];
                [SingleManager shareManager].NetworkStatus = NO;
            } else if (status == ReachableViaWiFi) {
                [SingleManager shareManager].NetworkStatus = YES;
            } else if (status == ReachableViaWWAN) {
                [SingleManager shareManager].NetworkStatus = YES;
            }
        }
    }
}

#pragma mark ----- 网络检测3(再次检测网络，如果还是断开，则视为网络已经断开) -----
- (void)appReachabilityChangedConfirm {
    if([self.routerReachability isKindOfClass:[Reachability class]]){
        if ([self.routerReachability currentReachabilityStatus] == NotReachable) {
            [SingleManager shareManager].NetworkStatus = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"网络中断" message:@"请检查网络" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *okBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alert addAction:cancelBtn];
                [alert addAction:okBtn];
                [self presentViewController:alert animated:YES completion:nil];
            });
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
